<?php

namespace fastphp\util;

/**
 * 文件操作
 */
class File
{
    private $file;
    private $pathInfo;

    /**
     * @param $file
     */
    public function __construct($file)
    {
        if (is_array($file)) {
            $this->file = $file;
            if (is_array($file['name'])) {
                $this->pathInfo = [];
                foreach ($file['name'] as $item) {
                    $this->pathInfo[] = pathinfo($item);
                }
            }else{
                $this->pathInfo = pathinfo($file['name']);
            }
        }
    }

    public function save($path = 'static/upload')
    {
        $newPath = $path . '/' . date('Ymd');
        if (Directory::createDirectoryRecursively($newPath)) {
            if (!isset($this->pathInfo['filename'])) {
                $res = [];
                foreach ($this->pathInfo as $key => $item) {
                    $fileName = md5(time() . $item['filename']) . $item['dirname'] . $item['extension'];
                    $fullPath = $newPath . '/' . $fileName;
                    if (move_uploaded_file($this->file['tmp_name'][$key], $fullPath)) {
                        $res[] = $fullPath;
                    }
                }
                if (empty($res)) {
                    return false;
                }
                return $res;
            } else {
                $fileName = md5(time() . $this->getFileName()) . $this->getDirname() . $this->getExtension();
                $fullPath = $newPath . '/' . $fileName;
                if (move_uploaded_file($this->file['tmp_name'], $fullPath)) {
                    return $fullPath;
                }
                return false;
            }

        }
        return false;
    }

    public function getExtension()
    {
        if (!isset($this->pathInfo['extension'])) {
            $arr = [];
            foreach ($this->pathInfo as $item) {
                $arr[] = $item['extension'];
            }
            return $arr;
        }
        return $this->pathInfo['extension'];
    }

    public function getFileName()
    {
        if (!isset($this->pathInfo['filename'])) {
            $arr = [];
            foreach ($this->pathInfo as $item) {
                $arr[] = $item['filename'];
            }
            return $arr;
        }
        return $this->pathInfo['filename'];
    }

    public function getDirname()
    {
        if (!isset($this->pathInfo['dirname'])) {
            $arr = [];
            foreach ($this->pathInfo as $item) {
                $arr[] = $item['dirname'];
            }
            return $arr;
        }
        return $this->pathInfo['dirname'];
    }

    public function getBasename()
    {
        if (!isset($this->pathInfo['basename'])) {
            $arr = [];
            foreach ($this->pathInfo as $item) {
                $arr[] = $item['basename'];
            }
            return $arr;
        }
        return $this->pathInfo['basename'];
    }
}